from datetime import date
import json

from django.core.handlers.wsgi import WSGIRequest

from administrators.models import Userinfo
from utils.enums import SCE
from utils.result import R
from administrators.views.token_check import make_token, verify_token, tjwss_30
from utils.cache_operation import CacheHandle
from django.db import IntegrityError
# 处理创建用户，登录鉴权等事务

import logging
logger = logging.getLogger('manage')


# token延期，如果token尚在期限内，那么就发给一个新的满期限token，不在的话就强制转到登录页面
@verify_token()
def token_extended(request: WSGIRequest, user_id):
    token = tjwss_30.loads(request.META.get("HTTP_TOKEN"))
    # 重新生成新的有30天期限的token
    new_token = make_token(token['id'], token['username'], token['password'])
    return R.success().data(new_token)


# 登录验证
def authentication(request):
    # data的格式 {'userName': '1', 'password': '1', 'sessionSave': True}
    data = json.loads(request.body)
    username = data['username']
    password = data['password']

    # 验证身份，验证成功则加入缓存发给token
    try:
        user_obj: Userinfo = Userinfo.objects.get(username=username, password=password)
        user_id = user_obj.id
        identity = json.loads(user_obj.identity)
        CacheHandle('user').update_dict({user_id: {'username': user_obj.username, 'password': user_obj.password}})
        token = make_token(user_id, user_obj.username, user_obj.password)

        logger.info(f'用户 {username} 登录成功')

        return R.success('登录验证成功').data({'token': token, 'identity': identity, 'user_id': user_id})
    except Userinfo.DoesNotExist:
        return R.error(SCE.F1, '用户不存在').data()


# 返回当前用户列表
@verify_token()
def userinfo(request, user_id):
    # 返回全部数据
    try:
        user_table = all_userinfo()
        return R.success().data(user_table)
    except Exception as e:
        print(e)

# 删除用户信息
@verify_token()
def delete_userinfo(request, user_id):
    data = json.loads(request.body)
    delete_id = int(data['id'])
    delete_username = data['username']

    try:
        Userinfo.objects.get(id=delete_id).delete()
        CacheHandle('user').delete_dict(delete_id)
        user_table = all_userinfo()
        return R.success(f'删除用户 {delete_username} 成功').data(user_table)
    except Userinfo.DoesNotExist:
        return R.error(SCE.F2, '要删除的用户不存在').data()


# 新增用户信息（不包括权限信息，那个是单独修改）
@verify_token()
def add_userinfo(request, user_id):
    data = json.loads(request.body)
    new_username = data['username']
    new_password = data['password']
    new_creator = data['creator']

    try:
        Userinfo.objects.create(identity=json.dumps([]), username=new_username, password=new_password,
                                       creation_date=date.today(), creator=new_creator)

        user_table = all_userinfo()
        return R.success("新增用户成功").data(user_table)
    except IntegrityError as e:
        if '重复键违反唯一约束' in str(e):
            return R.error(SCE.F3, '用户名称已经存在').data()


# 修改用户信息，并使得用户退出
@verify_token()
def modify_userinfo(request, user_id):
    data = json.loads(request.body)
    modify_username: str = data['username']
    modify_password: str = data['password']
    modify_id: int = data['id']
    new_creator: str = data['creator']

    # 返回值为修改的用户数量
    try:
        temp = Userinfo.objects.get(id=modify_id)
        temp.username = modify_username
        temp.password = modify_password
        temp.creator = new_creator
        temp.creation_date = date.today()
        temp.save()
        CacheHandle('user').delete_dict(modify_id)
        user_table = all_userinfo()
        return R.success('修改用户成功').data(user_table)
    except Userinfo.DoesNotExist:
        return R.error(SCE.F4, '要修改的用户不存在').data()
    except IntegrityError as e:
        if '重复键违反唯一约束' in str(e):
            return R.error(SCE.F5, '要修改的用户中用户名重复').data()


# 返回当前用户列表
def all_userinfo():
    user_table = list(Userinfo.objects.values('id', 'identity', 'username', 'password',
                                              'creation_date', 'creator').order_by('username'))
    for i in user_table:
        i['creation_date'] = str(i['creation_date'])
        i['identity'] = json.loads(i['identity'])
    return user_table


# 修改用户权限，因为权限改变，需要用户重新登录，将其从缓存中删除

@verify_token()
def update_identity(request, user_id):
    data = json.loads(request.body)
    identity = json.dumps(data['identity'])
    user_id = data['id']
    creator = data['creator']

    try:
        temp = Userinfo.objects.get(id=user_id)
        temp.identity = identity
        temp.creator = creator
        temp.creation_date = date.today()
        temp.save()
        try:
            CacheHandle('user').delete_dict(user_id)
        except KeyError:
            pass
        user_table = all_userinfo()
        return R.success('修改用户成功').data(user_table)
    except Userinfo.DoesNotExist:
        return R.error(SCE.F6, '要修改权限的用户不存在').data()
